package subject.tengxun.middle;

import java.util.*;

/**
 * 功能：
 * 作者：yedou
 * 日期：2025/3/16 16:18
 */
public class findAnagrams {
    public static void main(String[] args) {
        String s = "cbaebabacd";
        String p = "abc";
        List<Integer> result = new ArrayList<>();

        if (s == null || p == null || s.length() < p.length()) {
            System.out.println(result);
        }
        HashMap<Character, Integer> pMap = new HashMap<>();
        for (char c : p.toCharArray()) {
            pMap.put(c, pMap.getOrDefault(c, 0) + 1);
        }
        HashMap<Character, Integer> sMap = new HashMap<>();

        int windowSize = p.length();

        // 初始化 sMap（第一个窗口）
        for (int i = 0; i < windowSize; i++) {
            char c = s.charAt(i);
            sMap.put(c, sMap.getOrDefault(c, 0) + 1);
        }

        if (sMap.equals(pMap)) {
            result.add(0);
        }

        for (int i = windowSize; i < s.length(); i++) {
            char leftChar = s.charAt(i - windowSize);
            sMap.put(leftChar, sMap.get(leftChar) - 1);
            if (sMap.get(leftChar) == 0) {
                sMap.remove(leftChar);
            }
            // 添加窗口右边的字符
            char rightChar = s.charAt(i);
            sMap.put(rightChar, sMap.getOrDefault(rightChar, 0) + 1);
            // 检查当前窗口
            if (sMap.equals(pMap)) {
                result.add(i - windowSize + 1);
            }
        }
        System.out.println(result);
    }
}